package com.xblibo.xruth.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

import com.xblibo.xruth.entity.Function;
import com.xblibo.xruth.service.FunctionService;

//1 加载资源与权限的对应关系
@Service("securityMetadataSource")
public class SecurityFunction implements FilterInvocationSecurityMetadataSource {
	
	@Resource(name="functionService")
	private FunctionService functionService;
	
	private Map<String, Collection<ConfigAttribute>> resourceMap;
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}
	//加载所有资源与权限的关系
	private void loadResourceDefine() {
		if(resourceMap == null) {
			
			resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
			List<Function> functions = functionService.findAll();
			for(Function function:functions){
				Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
				//以权限名封装为Spring的security Object
				ConfigAttribute configAttribute = new SecurityConfig(function.getShortName());
				configAttributes.add(configAttribute);
				resourceMap.put(function.getUri(), configAttributes);
			}
		}
	}
	
	//返回所请求资源所需要的权限
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		
		String requestUrl = ((FilterInvocation) object).getRequestUrl();
		System.out.println("requestUrl is " + requestUrl);
		if(resourceMap == null) {
			loadResourceDefine();
		}
		System.out.println(resourceMap.get(requestUrl));
		return resourceMap.get(requestUrl);
	}

	

}
